//
//  MedicineListViewController.m
//  EcmDoctor
//
//  Created by Mac on 16/3/2.
//  Copyright © 2016年 张进. All rights reserved.
//

#import "MedicineListViewController.h"
#import "AppUtils.h"
#import "MedicineListm.h"
#import "MedicineListTableViewCell.h"
@interface MedicineListViewController ()<UITableViewDataSource,UITableViewDelegate,UITextFieldDelegate,UITextViewDelegate>
{
    
    __weak IBOutlet UIView *_backView;
 
    __weak IBOutlet UITableView *_medicinelistTv;
    UILabel *_blackl;
    __weak IBOutlet UITextView *_textView;
}
@property (nonatomic, strong) NSMutableArray *dataArr;
@property (nonatomic, strong) NSMutableArray *indexArr;
//存搜索出来的结果
@property (nonatomic, strong) NSMutableArray *resultArr;

@end

@implementation MedicineListViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.view.backgroundColor = [AppUtils getBackground];
    self.navigationItem.titleView=[AppUtils generateNavigationItemTitleViewWithTitle:@"中药饮片"];
    UIImage *tableIcon = [UIImage imageNamed:@"btn_back"];
    self.navigationItem.leftBarButtonItem =[[UIBarButtonItem alloc] initWithImage:tableIcon style:UIBarButtonItemStylePlain target:self action:@selector(changeToNavRootController)];
    self.navigationItem.leftBarButtonItem.tintColor = [UIColor colorWithPatternImage:tableIcon];
    self.navigationItem.rightBarButtonItem = [AppUtils generateNavigationBarButtonWithTitle:@"完成" withTarget:self action:@selector(selected)];
    _dataArr = [[NSMutableArray alloc]initWithCapacity:0];
    _resultArr = [[NSMutableArray alloc]initWithCapacity:0];
    _medicinelistTv.separatorStyle=UITableViewCellSeparatorStyleSingleLine;

    _backView.layer.borderColor=[UIColor colorWithRed:163/255.0 green:153/255.0 blue:141/255.0 alpha:1].CGColor;
    _backView.layer.borderWidth=1;
    _indexArr = [[NSMutableArray alloc] initWithCapacity:0];
    if(!_selectdAry)
    {
        _selectdAry=[NSMutableArray array];
    }
    //数据源
    for (int i = 'a'; i <= 'z'; i ++) {
        NSMutableArray *arr = [[NSMutableArray alloc] initWithCapacity:0];
        for (int j = 0; j < 9; j ++) {
            [arr addObject:[NSString stringWithFormat:@"%c%d",i,j]];
        }
        [_indexArr addObject:arr];
    }
    //UITableView
    
    //索引条的背景色，文字颜色，点击时的颜色
    _medicinelistTv.sectionIndexColor = [UIColor colorWithRed:114/255.0 green:102/255.0 blue:90/255.0 alpha:1];
    _medicinelistTv.sectionIndexMinimumDisplayRowCount=4;
    _medicinelistTv.sectionIndexBackgroundColor = [UIColor colorWithRed:235/255.0 green:215/255.0 blue:190/255.0 alpha:1.0];
    _medicinelistTv.sectionIndexTrackingBackgroundColor = [UIColor colorWithRed:235/255.0 green:215/255.0 blue:190/255.0 alpha:1.0];
    _medicinelistTv.rowHeight=40;
    
     NSString * DocumentsPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
    NSData *data=[NSData dataWithContentsOfFile:[DocumentsPath stringByAppendingString:@"/clientDrugInfo"]];
     NSArray *arr2 = [NSKeyedUnarchiver unarchiveObjectWithData:data];
     _dataArr=[NSMutableArray arrayWithArray:arr2];
   
    
}

static int search=0;

-(void)textViewDidBeginEditing:(UITextView *)textView
{
    textView.text=@"";
    
}
-(void)textViewDidChange:(UITextView *)textView
{
    search=0;
    [_resultArr removeAllObjects];
  
    //遍历数组
    for (NSArray *arr in _dataArr) {
        for (MedicineListm *medicinelist in arr) {
            NSRange range = [medicinelist.goods_name rangeOfString:textView.text];
            if (range.length) {
                
                [_resultArr addObject:medicinelist];
                search=1;
            }
        }
    }
    if(search==1)
        [_medicinelistTv reloadData];

}
-(void)textViewDidEndEditing:(UITextView *)textView
{
    if(!textView.text.length)
    {
        [self refreshTableView];
    }
}
-(void)refreshTableView
{
    if(search==1)
    {  search=0;
        [_medicinelistTv reloadData];
    }

}
-(void)selected
{

    [self.delegate refreshMedicineListWith:_selectdAry];
   
    [self changeToNavRootController];
}
//设置索引
//#pragma mark - 索引设置
- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView{
    NSMutableArray *arr = [[NSMutableArray alloc]initWithCapacity:0];
   
    
    for (int i = 'A'; i <= 'Z'; i++) {
        [arr addObject:[NSString stringWithFormat:@"%c",i]];
    }
    return arr;
}
//索引点击事件，index对应返回tableView的第几段
- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index{
//    [tableView
//     scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:index]
//     atScrollPosition:UITableViewScrollPositionTop animated:YES];
   if (search==0)
   {  [self showLetter:title];
       return index ;
   }
    else
        return 0;
}

-(void)showLetter:(NSString *)title
{
    if(_blackl==nil)
    {
        _blackl=[[UILabel alloc]initWithFrame:CGRectMake(0, 0, 80, 80)];
        _blackl.center=self.view.center;
        _blackl.font=[UIFont systemFontOfSize:60];
        _blackl.backgroundColor=[UIColor clearColor];
        _blackl.tintColor=[UIColor blackColor];
        _blackl.tintAdjustmentMode=NSTextAlignmentCenter;
    }
    _blackl.text=title;
    [self.view addSubview:_blackl];
    [NSThread detachNewThreadSelector:@selector(disapper) toTarget:self withObject:nil];
}
-(void)disapper
{
    usleep(300000);
    dispatch_async(dispatch_get_main_queue(), ^{
      [_blackl removeFromSuperview];
    });
    
    
    
}
#pragma mark - UITableView delegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    //如果响应这个方法的tableView不是我们创建的tableView，那么就是搜索控制器创建的tableView
    if (search==1) {
        return 1;
    }
    return _dataArr.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (search==1){
        return _resultArr.count;
    }
    return [[_dataArr objectAtIndex:section] count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
   
    UITableViewCell *cell ;
    MedicineListm *medicinelist;
    MedicineListTableViewCell *medicinecell=[tableView dequeueReusableCellWithIdentifier:@"mymedicinelist" forIndexPath:indexPath];
   if (search==1) {
       medicinelist=_resultArr[indexPath.row];
    }else{
        medicinelist=[[_dataArr objectAtIndex:indexPath.section] objectAtIndex:indexPath.row];
        
    }
    int a=0;
    for(int i=0;i<_selectdAry.count;i++)
    {
        MedicineListm *medicinelist1=_selectdAry[i];
        if([medicinelist.drug_sid isEqualToString:medicinelist1.drug_sid])
        { medicinecell.selectedImageView.image=[UIImage imageNamed:@"select_press"];
            a=1;
           
        }
    }
    if(a==0)
    {
         medicinecell.selectedImageView.image=[UIImage imageNamed:@"select_normal"];
        
        
    }

    medicinecell.medicinel.text =medicinelist.goods_name;
    medicinecell.selectionStyle=UITableViewCellSelectionStyleNone;
    cell=medicinecell;
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
   MedicineListTableViewCell *medicinecell =[tableView cellForRowAtIndexPath:indexPath];
   
    MedicineListm *medicinelist;
    if (search==1) {
        medicinelist=_resultArr[indexPath.row];
    }else{
        medicinelist= [[_dataArr objectAtIndex:indexPath.section] objectAtIndex:indexPath.row];
        
    }
    
    int a=0;
    
    for(int i=0;i<_selectdAry.count;i++)
    {
        MedicineListm *medicinelist1=_selectdAry[i];
        if([medicinelist.drug_sid isEqualToString:medicinelist1.drug_sid])
        {
            [_selectdAry removeObjectAtIndex:i];
            a=1;
             medicinecell.selectedImageView.image=[UIImage imageNamed:@"select_normal"];
        }
    }
    if(a==0)
    {
        [_selectdAry addObject:medicinelist];
        medicinecell.selectedImageView.image=[UIImage imageNamed:@"select_press"];
        
    }
 

}

-(void)changeToNavRootController{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
-(void)viewWillAppear:(BOOL)animated
{
    [self refreshTableView];
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
